import store from "@/store";
import erdfServer from "erdf-server";
const REMOTE_SCHEMA_URL = "/server/function-quality/base/JsonSchemaData/selects";
const SCHEMA_LIST = {
  term: '{"AND":[["isDelete","=",0]]}',
  sort: "insertTime desc",
  page: null,
};

// 获取远程schema列表
export const getRemoteSchemaList = async () => {
  let config = {
    headers: {
      "X-Source": "NoSignIn",
    },
  };
  try {
    // 尝试发送配置请求并捕获可能的错误
    const res = await erdfServer(config).erdfRequest(REMOTE_SCHEMA_URL, SCHEMA_LIST, "post");

    return res.list;
  } catch (e) {
    console.log(e);
    return [];
  }
};
// 获取指定schema
export const getSchema = (code) => {
  if(!store.state.schema[code]) return {};
  return store.state.schema[code].root || null;
};
// 提取f-definition函数
export const extractFunctionsFromSchema = (schema, funcMap, componentInstance) => {
  function extractFunctions(object) {
    // 检查当前层级的 'f-definition'
    if (object["f-definition"]) {
      Object.keys(object["f-definition"]).forEach((key) => {
        const funcName = key.split("-")[0];
        const funcParam = key.split("-").slice(1).join(",");
        const funcBody = object["f-definition"][key];
        // 构造函数体并添加到 funcMap 中
        // 使用闭包捕获 componentInstance
        funcMap[funcName] = new Function(funcParam, funcBody).bind(componentInstance);
      });
    }
    // 递归检查 'properties' 是否存在，并遍历它
    if (object.properties && typeof object.properties === "object") {
      Object.keys(object.properties).forEach((key) => {
        extractFunctions(object.properties[key]);
      });
    }
  }

  // 开始从根节点提取函数
  extractFunctions(schema);
};

// 将函数转换为字符串
export const functionToString = (obj) => {
  return JSON.stringify(obj, (key, value) => {
    if (typeof value === "function") {
      return value.toString(); // 将函数转换为字符串
    }
    return value;
  });
};

// 将字符串转换为函数
export const stringToFunction = (obj) => {
  return JSON.parse(obj, (key, value) => {
    // 检查是否为函数字符串并转换回函数
    if (typeof value === "string" && (value.startsWith("function") || value.includes("render"))) {
      try {
        return new Function("return " + value)(); // 将字符串解析为函数
      } catch (error) {
        console.error("Failed to parse function:", value, error);
      }
    }
    return value;
  });
};